package com.itheima.Filter;


import com.itheima.Utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;

import java.io.IOException;
@Slf4j
//@WebFilter("/*")//拦截所有
public class tokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取url
        String url = request.getRequestURL().toString();
        //2.判断是否包含login
        if (url.contains("login")){
            log.info("当前请求是登录,放行");
            filterChain.doFilter(request, response);
            return;
        }
        //3.获取jwt令牌
        String token = request.getHeader("token");
        //4.判断令牌是否为null
        if (token == null || token.isEmpty()) {
            log.info("令牌为null或者为空");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //5.解析令牌
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("解析令牌时出错");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        log.info("携带了令牌且校验通过:{}",token);
        filterChain.doFilter(request, response);

    }
}
